﻿using System.Data.Objects.SqlClient;
using System.Linq;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.BaseQueryModel;

namespace ZBJF.Warranty.BLL
{
    public partial class SystemRoleService
    {
        public SystemRole LoadByID(int id)
        {
            return LoadEntities(o => o.ID == id).FirstOrDefault();
        }

        public IQueryable<SystemRole> LoadAll(bool showDisabled = true)
        {
            var expressionWhere = PredicateExtensions.True<SystemRole>();
            if (!showDisabled)
                expressionWhere = expressionWhere.And(o => o.IsAvailable);
            return LoadEntities(expressionWhere);
        }

        public bool IsExistRoleName(string roleName, int id = 0)
        {
            var expressionWhere = PredicateExtensions.True<SystemRole>().And(o => o.RoleName.Equals(roleName));
            if (id > 0)
                expressionWhere = expressionWhere.And(o => o.ID != id);
            return LoadEntities(expressionWhere).Any();
        }

        public bool IsExistRoleCode(string roleCode, int id = 0)
        {
            var expressionWhere = PredicateExtensions.True<SystemRole>().And(o => o.RoleCode.Equals(roleCode));
            if (id > 0)
                expressionWhere = expressionWhere.And(o => o.ID != id);
            return LoadEntities(expressionWhere).Any();
        }

        public bool Disabled(int id, bool isAvailable = false)
        {
            var entity = LoadByID(id);
            if (entity != null)
            {
                entity.IsAvailable = isAvailable;
                return UpdateEntities(entity);
            }
            return false;
        }
        public IQueryable<SystemRole> GetPagingList(BaseQueryParams model, out int total)
        {
            var expressionWhere = PredicateExtensions.True<SystemRole>();
            if (!string.IsNullOrEmpty(model.Keyword))
            {
                expressionWhere =
                    expressionWhere.And(o => (o.RoleName + SqlFunctions.Space(1) +
                             o.RoleCode).Contains(model.Keyword));
            }

            return LoadPagerEntities<SystemRole>(model.PageIndex, model.iDisplayLength, out total, expressionWhere, model.iSorts);
        }
    }
}